package com.zx.work1.servlet;

import com.zx.work1.bean.Student;
import com.zx.work1.service.StudentService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebServlet(name = "delStudentServlet", urlPatterns = "/delStudent")
public class delStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        // 1.获取请求中的用户名和密码信息并打印出来
        String studentNum = request.getParameter("studentNum");
        System.out.println("获取到的学号为：" + studentNum);
        String studentName = request.getParameter("studentName");
        System.out.println("获取到的姓名为：" + studentName);
        String studentSex = request.getParameter("studentSex");
        System.out.println("获取到的性别为：" + studentSex);
        String studentData = request.getParameter("studentData");
        System.out.println("获取到的出生日期为：" + studentData);
        String studentMail = request.getParameter("studentMail");
        System.out.println("获取到的邮箱为：" + studentMail);
        String studentRemark = request.getParameter("studentRemark");
        System.out.println("获取到的备注为：" + studentRemark);

        StudentService studentService = new StudentService();
        Student student = studentService.queryStudentNumServeiece(Integer.valueOf(studentNum));
        if(student == null){
            System.out.println("删除学员失败");
            request.setAttribute("error", "删除学员失败，学号不存在！");
            // 实现服务器跳转  共享request和response对象
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("main.jsp");
            requestDispatcher.forward(request, response);
            return;
        }

        Student student1 = new Student(Integer.valueOf(studentNum),studentName,studentSex,studentData,studentMail,studentRemark);
        studentService.delStudentServeiece(student);

        System.out.println("删除成功");
        // 将登录成功的用户信息放入session对象中实现多个请求共享
        List<Object[]> studentList = studentService.queryStudentServeiece();
        request.getSession().setAttribute("originalList", studentList);
        for(Object[] objects: studentList){
            System.out.println(Arrays.toString(objects));
        }
        // 实现客户端跳转
        response.sendRedirect("main.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
